package cn.wolfcode.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Component
public class AliOSSUtils {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint ;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId ;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret ;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName ;
    //提供一个上传的图片方法,返回图片的访问路径
    public  String upload(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        //避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        //避免文件覆盖 获取文件后缀
        String extName= originalFilename.substring(originalFilename.lastIndexOf("."));
        //拼接成新的文件名
        String newFileName = UUID.randomUUID().toString() + extName;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //上传文件
        ossClient.putObject(bucketName, newFileName, inputStream);
        //关闭客户端
        ossClient.shutdown();
        //指定位置插入指定字符串序列
        StringBuffer sb = new StringBuffer(endpoint);
        StringBuffer urlsb = sb.insert(8, bucketName+".").append("/").append(newFileName);
        return urlsb.toString();
    }
}
